<template>
    <cus-modal ref="modal" :title="addForm.id ? '查看详情' : '添加保障评价'" @on-visible-change="onVisibleChange" width="80"
        @onOk="onOk" @onOther="onOther" :showOtherBtn="true" :otherBtnName="otherBtnName" :okBtnName="okBtnName">
        <!-- {{ addForm }} -->
        <Form ref="formValidate" :model="addForm" :rules="ruleValidate" :label-width="80" class="formData">
            <FormItem label="日期" prop="evaluationDate">
                <cus-datePick :startTime="addForm.evaluationDate" :showWeekNum="false" :showShortcuts="false"
                    format="yyyy-MM-dd" @onChange="onChangeDate" :disabled="Boolean(addForm.id)"></cus-datePick>
            </FormItem>
            <FormItem label="食堂" prop="unitCode">
                <Select v-model="addForm.unitCode" clearable placeholder="请选择伙食单位" style="width: 200px;"
                    :disabled="Boolean(addForm.id)">
                    <Option :value="item.unitCode" v-for="item in subCanteenList" :key="item.unitCode">{{ item.unitName }}
                    </Option>
                </Select>
            </FormItem>
            <FormItem label="检查人" prop="checkName">
                <Input v-model.trim="addForm.checkName" :disabled="Boolean(addForm.id)" placeholder="请输入检查人"
                    style="width: 200px;" clearable maxlength="20"></Input>
            </FormItem>
            <FormItem label="">
                <div style="width:200px"></div>
            </FormItem>
            <FormItem label="">
                <div style="width:200px"></div>
            </FormItem>
        </Form>
        <Tabs :value="selectIndex" @on-click="handleTabs" class="tabsBox">
            <TabPane :label="item.project" :name="item.project" v-for="(item,index) in tabsData" :key="index"></TabPane>
        </Tabs>
        <cusTable :border="true" :loading="showLoading" :columns="columns" :data="evaluationData"
            :handleSpan="handleSpan" >
            <template slot-scope="{ row, index }" slot="sourceSetting">
                <InputNumber :min="0" :max="1000" v-model="evaluationData[index].sourceSetting" :precision="2"
                    :active-change="false" @on-change="changeScoreSetting"></InputNumber>
            </template>
            <template slot-scope="{ row, index }" slot="source">
                <InputNumber :min="0" :max="row.sourceSetting" v-model="evaluationData[index].source" :precision="2"
                    :active-change="false" @on-change="changeScore"></InputNumber>
            </template>
        </cusTable>
        <!--导入-->
        <cus-uploadModal ref="cusUploadEvaluateModal" :temp-src="getApiDownloadEvaluateExcel" :uploadFnc="evaluationImport"
            titleName="导入保障评价"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            @onOk="onImportOk" @onError="onError"></cus-uploadModal>
        <!--excel导入错误提示-->
        <excelErrorModal ref="excelErrorModal"></excelErrorModal>
    </cus-modal>
</template>
<script>
import { evaluationDtl, evaluationSave, getApiDownloadEvaluateExcel, evaluationImport, } from '@/api/organ/business'
import excelErrorModal from './excelErrorModal.vue';
export default {
    name: 'addEvaluateModal',
    components: { excelErrorModal, },
    data() {
        return {
            getApiDownloadEvaluateExcel: getApiDownloadEvaluateExcel,
            evaluationImport,
            addForm: {
                id: null,   //保障评价Id
                evaluationDate: "", //日期
                unitCode: "",   //食堂编码
                unitName: "",   //食堂单位
                checkName: null, // 检查人
                // evaluateList: [],
            },
            otherBtnName: '导入',
            okBtnName: '保存',
            subCanteenList: [], //下级单位列表
            selectTabsDate: {},
            evaluationData: [],
            tabsData: [],
            selectIndex: '',
            showLoading: false,
            columns: [
                {
                    title: '序号',
                    width: 70,
                    type: 'index',
                    align: 'center'
                },
                {
                    title: '区分',
                    minWidth: 120,
                    key: 'projectChild',
                    align: 'center'
                },
                {
                    title: '认定内容和要求',
                    minWidth: 480,
                    key: 'evaluationItemName',
                    align: 'left'
                },
                {
                    title: '分值',
                    minWidth: 80,
                    slot: 'sourceSetting',
                    align: 'center'
                },
                {
                    title: '得分',
                    minWidth: 80,
                    slot: 'source',
                    align: 'center'
                },
            ],
            ruleValidate: {
                evaluationDate: [{ required: true, message: '评价日期不能为空', trigger: 'blur,change' },],
                unitCode: [{ required: true, message: '食堂不能为空', trigger: 'blur' },],
                checkName: [
                    { required: true, message: '检查人不能为空', trigger: 'blur' },
                    { required: true, message: '检查人只能汉字、数字、字母', pattern: '^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$', trigger: 'blur,change', },
                ],
                // checkName: [{ required: true, message: '检查人不能为空', trigger: 'blur' },],
            },
        };
    },
    mounted() {
        // this.addForm = this.$cu.deepClone(addForm);
    },
    methods: {
        // 分数改变回调
        changeScore(value) {
            console.log(value);
        },
        // 分值改变回调
        changeScoreSetting(value) {
            console.log(value)
        },
        // 切换tab栏
        handleTabs(value) {
            console.log(value);
            this.riseTwoDimension();
            this.selectTabsDate = this.tabsData.find((item) => item.project == value);
            this.evaluationData = this.flattenArray(this.selectTabsDate.projectChildVos);
            this.selectIndex = value;
        },
        riseTwoDimension() {
            // console.log('选中前的值', this.selectIndex);
            let beforeData = this.tabsData.find((item) => item.project == this.selectIndex);
            // 找到对应下标
            let findIndex = this.tabsData.findIndex((item) => { return item.project == this.selectIndex; });
            // console.log('切换前对应的下标', findIndex);
            const outputArray = this.transformTWoArray(this.evaluationData);
            // console.log('重新转换为二维', outputArray);
            this.tabsData[findIndex].projectChildVos = outputArray;
        },
        // 升维处理，一维转二维
        transformTWoArray(inputArray) {
            const result = [];
            inputArray.forEach((item) => {
                const { projectChild, evaluationItemId, evaluationItemName, sourceSetting, source } = item;
                // const { parentUnitCode, projectChild, evaluationItemId, evaluationItemName, scoreSetting, score } = item;
                const existingProject = result.find((project) => project.projectChild === projectChild);
                if (existingProject) {
                    existingProject.evaluationItemVos.push({
                        evaluationItemId,
                        evaluationItemName,
                        sourceSetting,
                        source,
                    });
                } else {
                    const newProject = {
                        // parentUnitCode,
                        projectChild,
                        evaluationItemVos: [
                            {
                                evaluationItemId,
                                evaluationItemName,
                                sourceSetting,
                                source,
                            },
                        ],
                    };
                    result.push(newProject);
                }
            });
            return result;
        },
        // 二维数据降维处理
        flattenArray(inputArray) {
            let result = [];
            for (let item of inputArray) {
                // let selectItem = { ...item, };
                this.flattenItem(item, result);
            }
            return result;
        },
        flattenItem(item, result) {
            let flattenedItem = { ...item };
            if (item.evaluationItemVos && item.evaluationItemVos.length > 0) {
                delete flattenedItem.evaluationItemVos;
                for (let child of item.evaluationItemVos) {
                    result.push({ ...flattenedItem, ...child, });
                    this.flattenItem({ ...flattenedItem, ...child, }, result); // 添加一个指向父级的属性，例如 'parent'
                }
            }
        },
        // 合并行数据
        handleSpan({ row, column, rowIndex, columnIndex }) {
            // console.log(row,column,rowIndex,columnIndex)
            if (columnIndex == 1) {
                // console.log(111,'clol');
                const rowspan = this.getRowspan(row, rowIndex);
                // console.log(rowspan);
                if (rowspan >= 1) {
                    return {
                        rowspan,
                        colspan: 1,
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                }
            };

        },
        getRowspan(row, rowIndex) {
            const currentId = row.projectChild;
            let rowspan = 1; // 默认rowspan为1，也就是每个单元格只占一行
            // 如果当前行不是第一行，则先查看前一行，如果前一行的值（同列单元格）与当前行（同列单元格）相同，则将当前单元格与前一行合并（当前单元格占0行，rowspan=0）
            if (rowIndex > 0) {
                const previousRow = this.evaluationData[rowIndex - 1];
                const previousId = previousRow.projectChild;
                if (currentId === previousId) {
                    return 0;
                }
            };
            // 然后向后查看，如果后面行（同列单元格）的值与当前行（同列单元格）相同，则每找到一行rowspan加1，直到找到与当前行（同列单元格）的值不同的行为止。（也就是说只能合并连续的行）
            for (let i = rowIndex + 1; i < this.evaluationData.length; i++) {
                const nextRow = this.evaluationData[i];
                const nextId = nextRow.projectChild;
                if (currentId === nextId) {
                    rowspan++;
                } else {
                    break;
                }
            };
            return rowspan;
        },
        // 选择日期变化
        onChangeDate(date) {
            console.log(date);
            this.addForm.evaluationDate = date;
            console.log(this.addForm);
        },
        onVisibleChange(v) {
            // console.log(this.addForm);
            if (!v) {
                // this.addForm = this.$cu.deepClone(addForm);
                this.addForm.id = null;
                this.$refs['formValidate'].resetFields();
                console.log('关闭弹窗',this.addForm);
            }
        },
        show() {
            this.$refs["modal"].show = true;
            console.log(this.addForm);
            this.getGuaranteeEvaluationListApi();
        },
        getGuaranteeEvaluationListApi() {
            this.showLoading = true;
            evaluationDtl({
                evaluationId: this.addForm.id,
            }).then((res) => {
                if (res.code === 1) {
                    this.showLoading = false;
                    // console.log(res);
                    this.addForm = res.data.protectionEvaluation;
                    console.log(this.addForm);
                    this.tabsData = res.data.projectEvaluationItemVos;
                    this.selectTabsDate = this.tabsData[0];
                    this.selectIndex = this.selectTabsDate.project;
                    console.log(this.selectTabsDate);
                    this.evaluationData = this.flattenArray(this.selectTabsDate.projectChildVos);
                    console.log(this.evaluationData);
                }
            }).catch((err) => {
                console.log(err);
                this.showLoading = false
            });
        },
        onImportOk(res) {
            this.tabsData = res.data.projectEvaluationItemVos;
            this.selectTabsDate = this.tabsData[0];
            this.selectIndex = this.selectTabsDate.project;
            this.evaluationData = this.flattenArray(this.selectTabsDate.projectChildVos);
            // this.getGuaranteeEvaluationListApi();
        },
        onError(res) {
            if (res.data) {
         
                this.$refs["excelErrorModal"].show();
                this.$refs["excelErrorModal"].data = res.data;
            }
        },
        onOk() {
            this.riseTwoDimension();
            this.$refs["formValidate"].validate((valid) => {
                if (valid) {
                    this.evaluationSaveApi();
                }
            });
        },
        onOther() {
            this.$refs["cusUploadEvaluateModal"].show();
        },
        // 调取保存保障评价接口
        evaluationSaveApi() {
            this.showLoading = true;
            if(this.addForm.unitCode == 'all') this.addForm.unitCode == '';
            evaluationSave({
                projectEvaluationItemVos: this.tabsData,
                protectionEvaluation: this.addForm,
            }).then((res) => {
                this.showLoading = false;
                if (res.code === 1) {
                    this.$Message.success('保存成功');
                    this.$refs["modal"].show = false;
                    this.$parent.onInit();
                }
            })
        },

    },
}
</script>
